package com.tanhua.server.Controller;

import cn.hutool.core.util.RandomUtil;
import com.tanhua.autoconfig.properties.SmsProperties;
import com.tanhua.autoconfig.templates.SmsTemplate;
import com.tanhua.model.db.User;
import com.tanhua.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    //根据手机号获取用户
    @GetMapping("/{mobile}")
    public User findByMobile(@PathVariable("mobile") String mobile) {
        //1.获取参数
        //2.业务逻辑
        User user = userService.findByMobile(mobile);
        //3.返回响应结果
        return user;

    }

    //用户登录--获取验证码
    @PostMapping("/login")
    private void login(@RequestBody Map map) {
        // 1.手机号
        String mobile = map.get("phone").toString();

        // 1.1 根据手机号查看用户状态判断
        User user = userService.findByMobile(mobile);
        userService.judgeUserStatus(user.getId());

        // 2.验证码
        //String code = RandomUtil.randomNumbers(6);
        String code = "123456";

        // 3.给手机发送验证码
        smsTemplate.sendSms(mobile, code);
        // 4.为了校验数据，保存验证码
        redisTemplate.opsForValue().set("CODE:" + mobile, code, 5, TimeUnit.MINUTES);
    }

    //根据手机验证码完成登陆操作
    @PostMapping("/loginVerification")
    public Map loginVerification(@RequestBody Map map) {
        String mobile = map.get("phone").toString();
        String code = map.get("verificationCode").toString();

        Map retMap = userService.loginVerification(mobile, code);

        return retMap;
    }
}
